<template>
  <div class="myContainer">
    <el-row class="myTitleBorderBottom myMarginBottom_10px">
      <el-col :span="12" class="myLineHeight_40px">
        <span v-if="type=='add'">新增</span>
        <span v-if="type=='update'">编辑</span>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         店铺名称:
      </el-col>
      <el-col :span="7">
        <template>
          <el-select 
            v-model="shopName"
            clearable
            placeholder="请选择店铺名称">
            <el-option
              v-for="item in shopNameList"
              :key="item.STORE_ID"
              :label="item.STORENAME"
              :value="item.STORE_ID">
            </el-option>
          </el-select>
        </template>
      </el-col>
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         商品名称:
      </el-col>
      <el-col :span="7">
        <el-input v-model="goodsName" placeholder="请输入商品名称"></el-input>
      </el-col>
    </el-row>
    
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         商品二级类别:
      </el-col>
      <el-col :span="7">
        <template>
          <el-select 
            v-model="classTwo"
            clearable
            @change="onClassLevel"
            placeholder="请选择商品二级类别">
            <el-option
              v-for="item in classTwoList"
              :key="item.CATEGORY_ID"
              :label="item.CATEGORYNAME"
              :value="item.CATEGORY_ID">
            </el-option>
          </el-select>
        </template>
      </el-col>
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         商品三级类别:
      </el-col>
      <el-col :span="7">
        <template>
          <el-select 
            v-model="classThree"
            clearable
            placeholder="请选择商品三级类别">
            <el-option
              v-for="item in classThreeList"
              :key="item.CATEGORY_ID"
              :label="item.CATEGORYNAME"
              :value="item.CATEGORY_ID">
            </el-option>
          </el-select>
        </template>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px" :gutter="10">
      <el-col :span="3" class="myTextAlignRight myLineHeight_40px">
        商品图片 :
      </el-col>
      <el-col :span="7">
        <el-upload
          class="avatar-uploader"
          :action="responseUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>  
        <span style="color: #f00">上传图片尺寸比例1:1,建议图片大小为100KB,格式为JPG/PNG。</span>
      </el-col>
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         条码:
      </el-col>
      <el-col :span="7">
        <el-input v-model="barcode" placeholder="请输入条码"></el-input>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px" :gutter="10">
      <el-col :span="3" class="myTextAlignRight myLineHeight_40px">
        轮播图 :
      </el-col>
      <el-col :span="17" class="my">
        <el-upload
          class="upload-demo"
          :action="AlbumUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :before-upload="beforeAvatarUpload"
          :file-list="fileList2"
          list-type="picture">
          <el-button type="primary" class="myBgGreen">点击上传</el-button>
        </el-upload>
        <span style="color: #f00">上传图片尺寸比例75:70,建议图片大小为100KB,格式为JPG/PNG。</span>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         简要描述:
      </el-col>
      <el-col :span="17">
        <el-input v-model="DESCRIPTION" type="textarea" placeholder="请输入简要描述"></el-input>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         商品市场价格:
      </el-col>
      <el-col :span="7">
        <el-input v-model="MARKETPRICE" placeholder="请输入商品市场价格"></el-input>
      </el-col>
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         商品销售价格:
      </el-col>
      <el-col :span="7">
        <el-input v-model="PRICE" placeholder="请输入商品销售价格"></el-input>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         商品库存数量:
      </el-col>
      <el-col :span="7">
        <el-input v-model="AMOUNT" placeholder="请输入商品库存数量"></el-input>
      </el-col>
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         商品规格:
      </el-col>
      <el-col :span="7">
        <el-input v-model="SPECIFICATIONS" placeholder="请输入商品规格"></el-input>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
         编辑器:
      </el-col>
      <el-col :span="17">
        <!-- quill-editor插件标签 分别绑定各个事件-->
        <quill-editor 
          v-model="content" 
          ref="myQuillEditor" 
          :options="editorOption" 
          @change="onEditorChange($event)">
        </quill-editor>
        <!-- 文件上传input 将它隐藏-->
        <el-upload 
          :action="qnLocation" 
          :before-upload='beforeUpload' 
          :data="uploadData" 
          :on-success='upScuccess'
          ref="upload" 
          style="display:none">
          <el-button 
            size="small" 
            type="primary" 
            id="imgInput" 
            element-loading-text="插入中,请稍候">
            点击上传
          </el-button>
        </el-upload>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         是否精品:
      </el-col>
      <el-col :span="7">
        <template>
          <el-select 
            v-model="ISBEST"
            clearable
            placeholder="请选择是否精品">
            <el-option
              v-for="item in ISBESTList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-col>
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         是否热卖:
      </el-col>
      <el-col :span="7">
        <template>
          <el-select 
            v-model="ISHOT"
            clearable
            placeholder="请选择是否热卖">
            <el-option
              v-for="item in ISHOTList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         是否上架:
      </el-col>
      <el-col :span="7">
        <template>
          <el-select 
            v-model="ISONSALE"
            clearable
            placeholder="请选择是否上架">
            <el-option
              v-for="item in ISONSALEList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-col>
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
         删除标志:
      </el-col>
      <el-col :span="7">
        <template>
          <el-select 
            v-model="DELETED"
            clearable
            placeholder="请选择删除标志">
            <el-option
              v-for="item in DELETEDList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="7" :offset="3">
        <el-button type="primary" class="myBgGreen" v-if="type=='update'" @click="onEditAd">保 存</el-button>
        <el-button type="primary" class="myBgGreen" v-if="type=='add'" @click="onCreate">新 增</el-button>
        <el-button type="primary" class="myBgGreen" @click="onBack">返 回</el-button>
      </el-col>
    </el-row>
    
  </div>
</template>
<style scoped>
  .myContainer{
    background: #fff;
    padding: 10px;
  }
  .myTitleBorderBottom{
    color: #000;
    font-weight: 500;
    font-size: 16px;
    border-bottom: 1px solid #dbdbdb;
  }
  .myBgGreen{
    background: #00c2a9;
    border-color: #00c2a9;
    color: #fff;
    margin-top:2px;
  }
  .myBgGreen:hover{
    background: #33ceba;
  }
  .myTextAlignRight{
    text-align: right;
  }
  .myLineHeight_40px{
    line-height: 40px;
  }
  .myMarginTop_10px{
    margin-top: 10px;
  }
  .myLeftMsg{
    line-height: 40px;
    text-align: right;
    padding-right: 10px;
  }
  .myPaddingBottom_10px{
    padding-bottom: 10px;
  }
  .myVA_M{
    vertical-align: middle;
  }
  .myMarginBottom_10px{
    margin-bottom: 20px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border:1px solid #d8dce5;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<script>
  import { quillEditor } from 'vue-quill-editor'; //调用编辑器  
  import Quill from 'quill';
  import { EBIZ_API , EBIZ_SHOW_PIC_API } from '@/config/baseUrl';
  import { getClassList , getGoodsDetail , getCommerceList , addGoods , editGoods } from '@/api/commerce';
  import qs from "querystring";
  export default {
    data(){
      return{
        title: "超市商品管理",
        id: "",
        is_modifly:false,
        type:"",
        ad_name:"",
        shopName:"",
        shopNameList:[],
        goodsName:"",
        classTwo:"",
        classTwoList:[],
        classThree:"",
        classThreeList:[],
        imageUrl:"",
        barcode:"",
        describe:"",
        saveImageUrl:"",
        DESCRIPTION:"",
        MARKETPRICE:"",
        AMOUNT:"",
        PRICE:"",
        SPECIFICATIONS:"",
        ISBEST:"",
        ISBESTList:[{value:0,label:"否"},{value:1,label:"是"}],
        ISHOT:"",
        ISHOTList:[{value:0,label:"否"},{value:1,label:"是"}],
        ISONSALE:"",
        ISONSALEList:[{value:0,label:"否"},{value:1,label:"是"}],
        DELETED:"",
        DELETEDList:[{value:0,label:"未删除"},{value:1,label:"已删除"}],        
        responseUrl:EBIZ_API+'/appAdmin_pictures/save.do?pictype=goodsLogo',//上传图片的地址url
        AlbumUrl:EBIZ_API+'/appAdmin_pictures/save.do?pictype=goodsBanner',
        dialogImageUrl: '',
        dialogImageUrlList:[],
        dialogVisible: false,
        dialogImageList:[],
        fileList2: [],
        // content:'',
        // editorOption:{}
        content: '', // 文章内容
        editorOption: {
          placeholder: '请输入内容',
          modules: { // 配置富文本
            toolbar: [
              ['bold', 'italic', 'underline', 'strike'],
              ['blockquote', 'code-block'],
              [{ 'header': 1 }, { 'header': 2 }],
              [{ 'direction': 'rtl' }],
              [{ 'size': ['small', false, 'large', 'huge'] }],
              [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
              [{ 'color': [] }, { 'background': [] }],
              [{ 'font': [] }],
              [{ 'align': [] }],
              ['clean'],
              ['link', 'image']
            ]
          }
        },
        addRange: [],
        uploadData: {},
        photoUrl: '', // 上传图片地址
        uploadType: '', // 上传的文件类型（图片、视频）
        saveimgSuccess:"",
        saveimg:""
      }
    },
    computed: {
      qnLocation () {
        return EBIZ_API+'/appAdmin_pictures/save2.do?pictype=goodsDetail';//编辑器图片上传地址
      }
    },
    components: {
      quillEditor  
    },
    created(){
      document.title=this.title;
      this.type = this.$route.query.type;
      this.id = this.$route.query.id;
      if(this.type=='add'){

      }
      if(this.type=='update'){
        this.onGetGoodsDetail();
      }
      this.onGetClassTwo();
      this.onGetCommerceList();

      this.$refs = {
        myQuillEditor: HTMLInputElement,
        imgInput: HTMLInputElement
      }
    },
    // 页面加载后执行 为编辑器的图片图标和视频图标绑定点击事件
    mounted () {
      // 为图片ICON绑定事件 getModule 为编辑器的内部属性
      this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler)
    },
    methods:{     
      onEditAd(){
        let vm=this;
        if(!vm.shopName || !vm.goodsName || !vm.classTwo || !vm.classThree || !vm.barcode || !vm.DESCRIPTION || !vm.MARKETPRICE || !vm.PRICE || !vm.AMOUNT || !vm.SPECIFICATIONS){
          vm.$message.error("请将数据填写完整！")
          return;
        }
        let params={
          "GOODS_ID":vm.id,
          "GOODSTYPE":1,
          "STORE_ID":vm.shopName,
          "GOODSNAME":vm.goodsName,
          "CATEGORY_ID1":1,
          "CATEGORY_ID2":vm.classTwo,
          "CATEGORY_ID3":vm.classThree,
          "LOGOIMG":vm.saveImageUrl,
          "BARCODE":vm.barcode,
          "ALBUM":vm.dialogImageUrl,
          "DESCRIPTION":vm.DESCRIPTION,
          "MARKETPRICE":vm.MARKETPRICE,
          "PRICE":vm.PRICE,
          "AMOUNT":vm.AMOUNT,
          "SPECIFICATIONS":vm.SPECIFICATIONS,
          "ISBEST":vm.ISBEST,
          "ISONSALE":vm.ISONSALE,
          "ISHOT":vm.ISHOT,
          "DELETED":vm.DELETED,
          "DETAILDESC":vm.content      
        }
        let params1={
          goods:[JSON.stringify(params)]
        }
        editGoods(qs.stringify(params1)).then(response => {
          let res=response.data;
          if(res.SUCCESS){
            this.$message.success('执行成功！');
            this.$router.go(-1);
          }else{
            this.$message.error('执行失败！'+res.MSG);
          }
        }).catch(error => {
          this.$message.error('执行失败！');
        })
      },
      onCreate(){//添加
        let vm=this;
        if(!vm.shopName || !vm.goodsName || !vm.classTwo || !vm.classThree || !vm.barcode || !vm.DESCRIPTION || !vm.MARKETPRICE || !vm.PRICE || !vm.AMOUNT || !vm.SPECIFICATIONS){
          vm.$message.error("请将数据填写完整！")
          return;
        }
        let params={
          "GOODS_ID":'',
          "GOODSTYPE":1,
          "STORE_ID":vm.shopName,
          "GOODSNAME":vm.goodsName,
          "CATEGORY_ID1":1,
          "CATEGORY_ID2":vm.classTwo,
          "CATEGORY_ID3":vm.classThree,
          "LOGOIMG":vm.saveImageUrl,
          "BARCODE":vm.barcode,
          "ALBUM":vm.dialogImageUrl,
          "DESCRIPTION":vm.DESCRIPTION,
          "MARKETPRICE":vm.MARKETPRICE,
          "PRICE":vm.PRICE,
          "AMOUNT":vm.AMOUNT,
          "SPECIFICATIONS":vm.SPECIFICATIONS,
          "ISBEST":vm.ISBEST,
          "ISONSALE":vm.ISONSALE,
          "ISHOT":vm.ISHOT,
          "DELETED":vm.DELETED,
          "DETAILDESC":vm.content         
        }
        let params1={
          goods:[JSON.stringify(params)]
        }
        addGoods(qs.stringify(params1)).then(response => {
          let res=response.data;
          if(res.SUCCESS){
            this.$message.success('执行成功！');
            this.$router.go(-1);
          }else{
            this.$message.error('执行失败！'+res.MSG);
          }
        }).catch(error => {
          vm.$message.error("执行失败！");
        })
      },
      onBack(){//返回
        this.$router.go(-1);
      },
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        this.saveImageUrl=res.saveUrl;
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG && !isPNG) {
          this.$message.error('上传图片只能是 JPG/PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return (isJPG || isPNG) && isLt2M;
      },
      onGetClassTwo(){//拉取二级分类
        let vm=this;
        //vm.classThree="";
        let params={
          CATEGORYTYPE:1,
          CATEGORYGRADE:2
        }
        getClassList(qs.stringify(params)).then(response => {
          let res=response.data;
          vm.classTwoList=res.OBJECT;
        }).catch(error => {

        })
      },
      onClassLevel(val){//动态拉取3级分类
        let vm=this;
        if(this.type!='update'){
          vm.classThree="";
        }
        let params={
          CATEGORYTYPE:1,
          CATEGORYGRADE:3,
          PARENTID:val
        }
        getClassList(qs.stringify(params)).then(response => {
          let res=response.data;
          vm.classThreeList=res.OBJECT;
          console.log(res)
        }).catch(error => {

        })
      },
      onGetGoodsDetail(){//拉取商品详细
        let vm=this;
        let params={
          GOODS_ID:vm.id
        }
        getGoodsDetail(params).then(response => {
          let res=response.data.OBJECT;
          vm.shopName=res.STORE_ID;
          vm.goodsName=res.GOODSNAME;
          vm.imageUrl=EBIZ_SHOW_PIC_API+res.LOGOIMG;
          vm.classTwo=res.CATEGORY_ID2;
          vm.classThree=res.CATEGORY_ID3;
          vm.barcode=res.BARCODE;
          vm.DESCRIPTION=res.DESCRIPTION;
          vm.MARKETPRICE=res.MARKETPRICE;
          vm.PRICE=res.PRICE;
          vm.AMOUNT=res.AMOUNT;
          vm.SPECIFICATIONS=res.SPECIFICATIONS;
          vm.ISBEST=res.ISBEST;
          vm.ISONSALE=res.ISONSALE;
          vm.ISHOT=res.ISHOT;
          vm.DELETED=res.DELETED;

          //轮播图
          vm.dialogImageUrl=res.ALBUM;
          let albumList=res.ALBUM!=''?res.ALBUM.split(";"):[];
          for(let i=0; i<albumList.length; i++){
            vm.fileList2.push({"url":EBIZ_SHOW_PIC_API+albumList[i]});
          }
          vm.saveimgSuccess=res.ALBUM;
          
          
          vm.saveImageUrl=res.LOGOIMG;
          vm.content=res.DETAILDESC;
          //console.log("----",res,res.ALBUM,albumList)
          vm.onClassLevel(vm.classTwo);
        }).catch(error => {

        })
      },
      onGetCommerceList() {//拉取店铺
        let vm = this;
        const params = {
          rows:999,
          page:1,
          STORENAME:"",
          STORETYPE:1,
          DELETED:0
        }
        getCommerceList(params)
        .then(response => {
          let res = response.data;
          vm.shopNameList=res.rows;
          console.log(res)   
        })
        .catch(error => {
        });
      },

      onEditorChange({ editor, html, text }) {
        this.content = html ;
      },
      // 图片上传之前调取的函数,用于获取token 这个钩子还支持 promise
      beforeUpload (file) {
        
      },
      // 图片上传成功回调 插入到编辑器中
      upScuccess (e, file, fileList) {
        let objE=JSON.parse(e)
        this.fullscreenLoading = false
        let vm = this
        let url = ''
        // 获得文件上传后的URL地址
        url = objE.data.src
        if (url != null && url.length > 0) { // 将文件上传后的URL地址插入到编辑器文本中
          let value = url
          // 获取光标位置对象，里面有两个属性，一个是index 还有 一个length，这里要用range.index，即当前光标之前的内容长度，然后再利用 insertEmbed(length, 'image', imageUrl)，插入图片即可。
          vm.addRange = vm.$refs.myQuillEditor.quill.getSelection()
          value = value.indexOf('http') !== -1 ? value : 'http:' + value
          vm.$refs.myQuillEditor.quill.insertEmbed(vm.addRange !== null ? vm.addRange.index : 0, vm.uploadType, value, Quill.sources.USER) // 调用编辑器的 insertEmbed 方法，插入URL
        } else {
          this.$message.error(`${vm.uploadType}插入失败`)
        }
        this.$refs['upload'].clearFiles() // 插入成功后清除input的内容
      },
      // 点击图片ICON触发事件
      imgHandler (state) {
        this.addRange = this.$refs.myQuillEditor.quill.getSelection();
        if (state) {
          let fileInput = document.getElementById('imgInput');
          fileInput.click(); // 加一个触发事件
        }
        this.uploadType = 'image';
      },


      handleRemove(file, fileList) {//轮播图移除
        this.saveimg="";
        for(let i=0; i<fileList.length; i++){
          if(fileList[i].response){
            this.saveimg+=fileList[i].response.saveUrl+";";
          }else{
            this.saveimg+=fileList[i].url.split(EBIZ_SHOW_PIC_API)[1]+";";
          }
        }
        this.dialogImageUrl=this.saveimg.substring(0,this.saveimg.length-1);
        //console.log(this.dialogImageUrl)
      },
      handlePreview(file,fileList) {
        //console.log(file,fileList);
      },
      handleSuccess(file,fileList){//轮播图上传添加成功
        if(this.saveimgSuccess==""){
          this.saveimgSuccess=file.saveUrl;
          this.dialogImageUrl=this.saveimgSuccess;
        }else{
          this.saveimgSuccess+=";"+file.saveUrl;
          this.dialogImageUrl=this.saveimgSuccess;
        }
      }
    }
  
  }


</script>



